package org.mca.mcaweb.interceptor;

import i18n.MsgUtil;

import java.io.Serializable;
import java.util.ResourceBundle;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

import org.mca.mcaweb.annotation.ExceptionHandler;
import org.mca.mcaweb.util.ResourceBundleUtil;

@Interceptor
@ExceptionHandler
public class ExceptionHandlerInterceptor implements Serializable {
	
	private static final long serialVersionUID = -5323173892518180214L;
	
	private ResourceBundle bundle = ResourceBundleUtil.getResourceBunde();

	@AroundInvoke
	public Object intercept(InvocationContext ctx) throws Exception {
		
		Object result = null;
		
		try {
			
			result = ctx.proceed();
			
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getCause().getMessage().startsWith("org.hibernate.exception.ConstraintViolationException")) {
				MsgUtil.addErrorMessage("Interceptador", bundle.getString("exection.delete.depend"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.DataException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.incompatible.data"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.GenericJDBCException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.unknown"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.JDBCConnectionException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.communicate.bank"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.LockAcquisitionException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.unknown"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.NestableException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.unknown"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.NestableRuntimeException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.unknown"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.SQLGrammarException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.sql"));
			} else if(e.getCause().getMessage().startsWith("could not insert")){
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.could.not.insert"));
			} else {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("exection.unknown"));
			}

		} 
		
		return result;
	}
}
